package br.com.cfccultura.admin.control.actions;

import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.cfccultura.admin.control.exceptions.SessaoInvalidaException;
import br.com.cfccultura.admin.control.utils.DAOFactory;
import br.com.cfccultura.admin.model.dao.IAgendamentoProvaDAO;
import br.com.cfccultura.admin.model.dao.IAlunoDAO;
import br.com.cfccultura.admin.model.dao.IBancoDAO;
import br.com.cfccultura.admin.model.dao.ICalendarioDAO;
import br.com.cfccultura.admin.model.dao.IComputadorProvaDAO;
import br.com.cfccultura.admin.model.dao.ICursoDAO;
import br.com.cfccultura.admin.model.dao.IDirecionamentoChequeDAO;
import br.com.cfccultura.admin.model.dao.IFluxoCaixaDAO;
import br.com.cfccultura.admin.model.dao.IFornecedorDAO;
import br.com.cfccultura.admin.model.dao.IFuncionarioDAO;
import br.com.cfccultura.admin.model.dao.IOrdemServicoDAO;
import br.com.cfccultura.admin.model.dao.ISalaAulaDAO;
import br.com.cfccultura.admin.model.dao.IServicoDAO;
import br.com.cfccultura.admin.model.dao.ITipoFornecedorDAO;
import br.com.cfccultura.admin.model.dao.ITurmaDAO;
import br.com.cfccultura.admin.model.vo.Funcionario;
import br.com.cfccultura.admin.model.vo.PontoEletronico;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class DefaultAction extends DispatchAction {
	
	private static final Logger logger = Logger.getLogger(DefaultAction.class);
	
	private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
	private static final SimpleDateFormat shf = new SimpleDateFormat("HH:mm");
	private static final SimpleDateFormat sdfDojo = new SimpleDateFormat("yyyy-MM-dd");
	private static final SimpleDateFormat sdhf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	private static final DecimalFormat df = (DecimalFormat)DecimalFormat.getInstance(new Locale("pt","br"));
	
	@Autowired
	private DAOFactory daoFactory;
		
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		if(request.getSession().getAttribute("usuario") == null) {
			if(mapping.getPath().equals("/login") && request.getParameter("method").equals("iniciar") || request.getParameter("method").equals("login")) {
				
			} else {
				request.getSession().invalidate();
				addMessage(request, "login.usuario.sessao.invalida");
				return mapping.findForward("index"); 
			}
		}
		
		
		getMessages(request).clear();
		request.setAttribute("dataAtual", sdf.format(new Date()));
		request.setAttribute("dataAtualDojo", sdfDojo.format(new Date()));
		request.getSession().setAttribute("defaultLocale", new Locale("pt","BR"));
		
		Calendar c = Calendar.getInstance();
		c.add(Calendar.MONTH, 1);
		if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
			c.add(Calendar.DAY_OF_MONTH, 2);
		} else if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		request.setAttribute("data30Cheque", getDateFormatDojo().format(c.getTime()));
		
		c.setTime(new Date());
		c.add(Calendar.DAY_OF_MONTH, 15);
		if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
			c.add(Calendar.DAY_OF_MONTH, 2);
		} else if(c.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
			c.add(Calendar.DAY_OF_MONTH, 1);
		}
		
		request.setAttribute("data15Cheque", getDateFormatDojo().format(c.getTime()));
		request.setAttribute("acrescimo15Dias", 5);
		
		try {
			ActionForward action = super.execute(mapping, form, request, response);
			if(!mapping.getPath().equals("/login")) {
				if(request.getParameter("ajax") == null)
					initMenu(request);
			} else {
				if(!request.getParameter("method").equals("sair") && !request.getParameter("method").equals("iniciar") && getUsuario(request) != null) {
					if(request.getParameter("ajax") == null)
						initMenu(request);
				}
			}
			
			return action;
		} catch(SessaoInvalidaException exc) {
			return mapping.findForward("sair"); 
		}
	}
		
	private void initMenu(HttpServletRequest request) {
		
		PontoEletronico ponto = getFuncionarioDAO().consultaPontoAtual(getUsuario(request));
		if(ponto != null) {
			request.setAttribute("pontoEletronico", ponto);
		}
		
	}

	protected void addMessage(HttpServletRequest request, String key, String... args) {
		ActionMessages messages = new ActionMessages();
		ActionMessage message = new ActionMessage(key, args);
		messages.add(ActionMessages.GLOBAL_MESSAGE, message);
		addMessages(request, messages);
	}
	
	protected void printJsonObjectToStream(Object vo, HttpServletResponse response) throws Exception {
		GsonBuilder builder = new GsonBuilder();	
		Gson gson = builder.create();
		
		String json = gson.toJson(vo);
		System.out.println(json);
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		out.println(new String(json.getBytes("UTF-8"), "ISO-8859-1"));
	}
	
	protected void printMessage(String message, HttpServletResponse response) throws Exception {
		response.setStatus(450);
		response.setContentType("text/text");
		PrintWriter out = response.getWriter();
		out.println(message);
	}	
		
	public Funcionario getUsuario(HttpServletRequest request) {
		return (Funcionario)request.getSession().getAttribute("usuario");
	}
	public void setUsuario(HttpServletRequest request, Funcionario vo) {
		request.getSession().setAttribute("usuario", vo);
	}
	
	protected String gerarSenhaRandomica(){
		char[] chart ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','@','!','?','#','$','%'};
		int len = 10;
		char[] senha= new char[len];
		int chartLenght = chart.length;
		Random rdm = new Random();
		for (int x=0; x<len; x++)
			senha[x] = chart[rdm.nextInt(chartLenght)];

		return new String(senha);
	}
	
	public SimpleDateFormat getDateFormat() {
		return sdf;
	}
	public SimpleDateFormat getDateFormatDojo() {
		return sdfDojo;
	}
	
	public SimpleDateFormat getDateHourFormat() {
		return sdhf;
	}
	
	public DecimalFormat getDecimalFormat() {
		return df;
	}
	
	public SimpleDateFormat getSimpleHourFormat() {
		return shf;
	}
	
	public DAOFactory getDaoFactory() {
		return daoFactory;
	}
	public void setDaoFactory(DAOFactory daoFactory) {
		this.daoFactory = daoFactory;
	}
	
	public IFuncionarioDAO getFuncionarioDAO() {
		return getDaoFactory().getFuncionarioDAO();
	}
	public ISalaAulaDAO getSalaAulaDAO() {
		return getDaoFactory().getSalaAulaDAO();
	}
	public ICursoDAO getCursoDAO() {
		return getDaoFactory().getCursoDAO();
	}
	public ITipoFornecedorDAO getTipoFornecedorDAO() {
		return getDaoFactory().getTipoFornecedorDAO();
	}
	public IFornecedorDAO getFornecedorDAO() {
		return getDaoFactory().getFornecedorDAO();
	}
	public IServicoDAO getServicoDAO() {
		return getDaoFactory().getServicoDAO();
	}
	public IComputadorProvaDAO getComputadorProvaDAO() {
		return getDaoFactory().getComputadorProvaDAO();
	}
	public ITurmaDAO getTurmaDAO() {
		return getDaoFactory().getTurmaDAO();
	}
	public ICalendarioDAO getCalendarioDAO() {
		return getDaoFactory().getCalendarioDAO();
	}
	public IAgendamentoProvaDAO getAgendamentoProvaDAO() {
		return getDaoFactory().getAgendamentoProvaDAO();
	}
	public IAlunoDAO getAlunoDAO() {
		return getDaoFactory().getAlunoDAO();
	}
	public IBancoDAO getBancoDAO() {
		return getDaoFactory().getBancoDAO();
	}
	public IFluxoCaixaDAO getFluxoCaixaDAO() {
		return getDaoFactory().getFluxoCaixa();
	}
	public IOrdemServicoDAO getOrdemServicoDAO() {
		return getDaoFactory().getOrdemServico();
	}	
	public IDirecionamentoChequeDAO getDirecionamentoChequeDAO(){
		return getDaoFactory().getDirecionamentoChequeDAO();
	}

}
